<template>
  <div class="audit-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>应用审核</span>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" class="search-form">
        <el-form-item label="应用名称" prop="appName">
          <el-input v-model="queryParams.appName" placeholder="请输入应用名称" clearable />
        </el-form-item>
        <el-form-item label="开发者" prop="developerName">
          <el-input v-model="queryParams.developerName" placeholder="请输入开发者名称" clearable />
        </el-form-item>
        <el-form-item label="审核状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择审核状态" clearable>
            <el-option label="待审核" :value="0" />
            <el-option label="已通过" :value="1" />
            <el-option label="已拒绝" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="提交时间" prop="timeRange">
          <el-date-picker
            v-model="queryParams.timeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 审核列表 -->
      <el-table v-loading="loading" :data="auditList" style="width: 100%">
        <el-table-column prop="appName" label="应用名称" min-width="150">
          <template #default="{ row }">
            <div class="app-info">
              <el-image :src="row.appIcon" class="app-icon" fit="cover" />
              <span>{{ row.appName }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="developerName" label="开发者" min-width="120" />
        <el-table-column prop="version" label="版本" width="100" />
        <el-table-column prop="category" label="分类" width="120" />
        <el-table-column prop="submitTime" label="提交时间" width="180" />
        <el-table-column label="审核状态" width="100">
          <template #default="{ row }">
            <el-tag v-if="row.status === 0" type="warning">待审核</el-tag>
            <el-tag v-else-if="row.status === 1" type="success">已通过</el-tag>
            <el-tag v-else-if="row.status === 2" type="danger">已拒绝</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleDetail(row)">详情</el-button>
            <el-button v-if="row.status === 0" type="success" link @click="handleApprove(row)">通过</el-button>
            <el-button v-if="row.status === 0" type="danger" link @click="handleReject(row)">拒绝</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-if="total > 0"
        class="pagination"
        :current-page="queryParams.pageNum"
        :page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />

      <!-- 审核对话框 -->
      <el-dialog
        v-model="auditDialogVisible"
        :title="auditDialogTitle"
        width="500px"
        destroy-on-close
      >
        <el-form
          ref="auditFormRef"
          :model="auditForm"
          :rules="auditRules"
          label-width="100px"
        >
          <el-form-item label="审核意见" prop="comment">
            <el-input
              v-model="auditForm.comment"
              type="textarea"
              :rows="4"
              placeholder="请输入审核意见"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="auditDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitAudit">确定</el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 应用详情对话框 -->
      <el-dialog
        v-model="detailDialogVisible"
        title="应用详情"
        width="800px"
        destroy-on-close
      >
        <div v-if="currentApp" class="app-detail">
          <div class="app-header">
            <el-image :src="currentApp.appIcon" class="app-detail-icon" fit="cover" />
            <div class="app-header-info">
              <h2>{{ currentApp.appName }}</h2>
              <div class="app-meta">
                <span>开发者：{{ currentApp.developerName }}</span>
                <span>版本：{{ currentApp.version }}</span>
                <span>分类：{{ currentApp.category }}</span>
                <span>提交时间：{{ currentApp.submitTime }}</span>
              </div>
            </div>
          </div>
          
          <el-divider />
          
          <div class="app-description">
            <h3>应用描述</h3>
            <p>{{ currentApp.description }}</p>
          </div>
          
          <div class="app-screenshots">
            <h3>应用截图</h3>
            <el-scrollbar>
              <div class="screenshot-list">
                <el-image
                  v-for="(screenshot, index) in currentApp.screenshots"
                  :key="index"
                  :src="screenshot"
                  class="screenshot"
                  fit="cover"
                  :preview-src-list="currentApp.screenshots"
                  :initial-index="index"
                />
              </div>
            </el-scrollbar>
          </div>
          
          <div class="app-package">
            <h3>安装包信息</h3>
            <div class="package-info">
              <p>包名：{{ currentApp.packageName }}</p>
              <p>大小：{{ formatFileSize(currentApp.packageSize) }}</p>
              <p>MD5：{{ currentApp.packageMd5 }}</p>
            </div>
          </div>
          
          <div v-if="currentApp.status !== 0" class="audit-result">
            <h3>审核结果</h3>
            <div class="result-info">
              <p>状态：
                <el-tag v-if="currentApp.status === 1" type="success">已通过</el-tag>
                <el-tag v-else-if="currentApp.status === 2" type="danger">已拒绝</el-tag>
              </p>
              <p>审核人：{{ currentApp.auditorName }}</p>
              <p>审核时间：{{ currentApp.auditTime }}</p>
              <p>审核意见：{{ currentApp.comment || '无' }}</p>
            </div>
          </div>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';

// 查询参数
const queryParams = reactive({
  appName: '',
  developerName: '',
  status: undefined,
  timeRange: [],
  pageNum: 1,
  pageSize: 10
});

// 表单引用
const queryFormRef = ref<FormInstance>();
const auditFormRef = ref<FormInstance>();

// 数据列表
const loading = ref(false);
const auditList = ref<any[]>([]);
const total = ref(0);

// 审核对话框
const auditDialogVisible = ref(false);
const auditDialogTitle = ref('');
const auditForm = reactive({
  id: 0,
  status: 0,
  comment: ''
});

// 审核表单校验规则
const auditRules = {
  comment: [
    { required: true, message: '请输入审核意见', trigger: 'blur' }
  ]
};

// 应用详情对话框
const detailDialogVisible = ref(false);
const currentApp = ref<any>(null);

// 获取审核列表
const fetchAuditList = () => {
  loading.value = true;
  
  // 模拟数据，实际项目中应该从API获取
  setTimeout(() => {
    const mockData = [];
    for (let i = 1; i <= 20; i++) {
      mockData.push({
        id: i,
        appName: `测试应用${i}`,
        appIcon: 'https://via.placeholder.com/50',
        developerName: `开发者${i % 5 + 1}`,
        version: `1.${i % 10}.0`,
        category: ['工具', '办公', '教育', '娱乐', '社交'][i % 5],
        submitTime: new Date(Date.now() - i * 86400000).toLocaleString(),
        status: i % 3,
        description: '这是一个测试应用的详细描述，包含了应用的主要功能和特点。',
        screenshots: [
          'https://via.placeholder.com/800x400',
          'https://via.placeholder.com/800x400',
          'https://via.placeholder.com/800x400'
        ],
        packageName: `com.example.app${i}`,
        packageSize: 1024 * 1024 * (10 + i % 20),
        packageMd5: '0123456789abcdef0123456789abcdef',
        auditorName: i % 3 === 0 ? '' : '管理员',
        auditTime: i % 3 === 0 ? '' : new Date(Date.now() - i * 43200000).toLocaleString(),
        comment: i % 3 === 0 ? '' : (i % 3 === 1 ? '应用符合要求，审核通过' : '应用存在安全风险，审核拒绝')
      });
    }
    
    auditList.value = mockData;
    total.value = 100;
    loading.value = false;
  }, 500);
};

// 查询
const handleQuery = () => {
  queryParams.pageNum = 1;
  fetchAuditList();
};

// 重置查询
const resetQuery = () => {
  if (!queryFormRef.value) return;
  queryFormRef.value.resetFields();
  handleQuery();
};

// 查看详情
const handleDetail = (row: any) => {
  currentApp.value = row;
  detailDialogVisible.value = true;
};

// 通过审核
const handleApprove = (row: any) => {
  auditDialogTitle.value = '通过审核';
  auditForm.id = row.id;
  auditForm.status = 1;
  auditForm.comment = '';
  auditDialogVisible.value = true;
};

// 拒绝审核
const handleReject = (row: any) => {
  auditDialogTitle.value = '拒绝审核';
  auditForm.id = row.id;
  auditForm.status = 2;
  auditForm.comment = '';
  auditDialogVisible.value = true;
};

// 提交审核
const submitAudit = async () => {
  if (!auditFormRef.value) return;
  
  await auditFormRef.value.validate(async (valid) => {
    if (valid) {
      // 模拟API调用
      setTimeout(() => {
        ElMessage.success(auditForm.status === 1 ? '审核通过成功' : '审核拒绝成功');
        auditDialogVisible.value = false;
        
        // 更新列表中的状态
        const index = auditList.value.findIndex(item => item.id === auditForm.id);
        if (index !== -1) {
          auditList.value[index].status = auditForm.status;
          auditList.value[index].comment = auditForm.comment;
          auditList.value[index].auditorName = '管理员';
          auditList.value[index].auditTime = new Date().toLocaleString();
        }
      }, 500);
    }
  });
};

// 分页大小变更
const handleSizeChange = (size: number) => {
  queryParams.pageSize = size;
  fetchAuditList();
};

// 页码变更
const handleCurrentChange = (page: number) => {
  queryParams.pageNum = page;
  fetchAuditList();
};

// 格式化文件大小
const formatFileSize = (size: number) => {
  if (size < 1024) {
    return size + ' B';
  } else if (size < 1024 * 1024) {
    return (size / 1024).toFixed(2) + ' KB';
  } else if (size < 1024 * 1024 * 1024) {
    return (size / (1024 * 1024)).toFixed(2) + ' MB';
  } else {
    return (size / (1024 * 1024 * 1024)).toFixed(2) + ' GB';
  }
};

onMounted(() => {
  fetchAuditList();
});
</script>

<style scoped>
.audit-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.app-info {
  display: flex;
  align-items: center;
}

.app-icon {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  margin-right: 10px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.app-detail {
  padding: 0 20px;
}

.app-header {
  display: flex;
  align-items: center;
}

.app-detail-icon {
  width: 80px;
  height: 80px;
  border-radius: 16px;
  margin-right: 20px;
}

.app-header-info h2 {
  margin: 0 0 10px 0;
  font-size: 20px;
}

.app-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  color: #606266;
  font-size: 14px;
}

.app-description,
.app-screenshots,
.app-package,
.audit-result {
  margin-top: 20px;
}

.app-description h3,
.app-screenshots h3,
.app-package h3,
.audit-result h3 {
  font-size: 16px;
  margin-bottom: 10px;
}

.screenshot-list {
  display: flex;
  gap: 10px;
  padding-bottom: 10px;
}

.screenshot {
  width: 200px;
  height: 120px;
  border-radius: 8px;
  cursor: pointer;
}

.package-info,
.result-info {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 8px;
}

.package-info p,
.result-info p {
  margin: 5px 0;
}
</style> 